from curl_cffi import requests

from urllib.parse import urlparse
import hashlib
import time
import json
import execjs
with open("main.js","r",encoding="utf-8") as f:
    js = f.read()
js_com=execjs.compile(js)
proxies={
    'http': '127.0.0.1:7890',
    'https': '127.0.0.1:7890'
}
url = "https://prod-na-api.popmart.com/shop/v1/search"

path = urlparse(url).path
print("path==>",path)  # 输出: /shop/v1/search
t=int(time.time())
data = {
    "pageSize": 20,
    "page": 2,
    "strategy": "",
    "term": "HA",
    "categoryIds": [],
    "brandIds": [],
}
tdata = json.dumps({k: v for k, v in data.items() if k not in ['s', 't']})
print("tdata==>",tdata)
tdsign=js_com.call("getSign",path,tdata)
print("tdsign==>",tdsign['sign'])
xsign=js_com.call("get_xsign",t)
print("xsign==>",xsign)
s=js_com.call("get_s",t)
print("s==>",s)
data['s']= s
data['t']= t
headers = {
    "accept": "application/json, text/plain, */*",
    "content-type": "application/json",
    "country": "US",
    "language": "en",
    "origin": "https://www.popmart.com",
    "referer": "https://www.popmart.com/",
    "td-session-path": "/shop/v1/search",
    "td-session-query;": "",
    "td-session-sign": tdsign['sign'],
    "tz": "Asia/Shanghai",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0",
    "x-client-country": "US",
    "x-client-namespace": "america",
    "x-device-os-type": "web",
    "x-doughnuts;": "",
    "x-project-id": "naus",
    "x-sign": xsign,
}

print("入参data==>",data)
data = json.dumps(data, separators=(',', ':'))
response = requests.post(url, headers=headers, data=data,proxies=proxies)

print(response.text)
print(response)
